<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import { useSourceStore } from '~/store/source';

const sourcesStore = useSourceStore()
const { sources, currentSourceIdx } = storeToRefs(sourcesStore)
const tableData = ref<SourceType[]>([])
const search = ref('')

if (sourcesStore.isSourcesEmpty()) {
	sourcesStore.refreshSources().then(() => {
		tableData.value = [...sources.value]
	})
} else {
	tableData.value = [...sources.value]
}

function refreshTableData() {
	sourcesStore.refreshSources().then(() => {
		tableData.value = [...sources.value]
	})
}

function handleSearch() {
	if (search.value === "") {
		tableData.value = [...sources.value]
	} else {
		tableData.value = sources.value.filter(it => it.name.split(search.value).length > 1)
	}
}

async function handleEdit(idx: number) {
	sourcesStore.setCurrentIdx(idx)
}

</script>

<template>
	<div>
		<div flex mb-2 items-center>
			<el-button @click="refreshTableData" type="primary">刷新所有源</el-button>
			&nbsp;&nbsp;
			<span>当前源： {{ sources[currentSourceIdx].name }}</span>
		</div>
		<ElCard>
			<el-table :data="tableData" style="width: 100%">
				<el-table-column prop="name" label="网站名">
				</el-table-column>
				<el-table-column prop="url" label="网址">
				</el-table-column>
				<el-table-column align="right">
					<template #header>
						<div flex>
							<el-input v-model="search" size="small" placeholder="Type to search" />
							&nbsp;
							<el-button @click="handleSearch" size="small" type="primary">搜索</el-button>
						</div>
					</template>
					<template #default="scope">
						<el-button v-if="scope.row.url === sources[currentSourceIdx].url" disabled size="small">已是当前源</el-button>
						<el-button v-else size="small" @click="handleEdit(scope.$index)" type="primary">设置为当前源</el-button>
					</template>
				</el-table-column>
			</el-table>
		</ElCard>
	</div>
</template>